package com.example.myweather

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle

import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.example.myweather.adapter.Day_precipitation_adapter
import com.example.myweather.adapter.Hour_skycon_tem_adapter
import com.example.myweather.adapter.Min_precipitation_adapter
import com.example.myweather.bean.WeatherApi
import com.example.myweather.tools.AppUtils
import com.example.myweather.tools.CheckPermissionsActivity
import com.example.myweather.tools.HttpUtils
import com.example.myweather.tools.MainApplication
import com.example.myweather.tools.Weather_Dict
import com.google.gson.Gson
import com.scwang.smartrefresh.header.FlyRefreshHeader
import com.scwang.smartrefresh.header.TaurusHeader
import com.scwang.smartrefresh.header.WaveSwipeHeader
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import com.socks.library.KLog
import com.umeng.message.PushAgent
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

import android.os.Handler
import android.os.Looper
import android.os.Message
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast

import org.w3c.dom.Text

import java.io.IOException

import okhttp3.Call
import okhttp3.Response

class WeatherActivity : CheckPermissionsActivity() {

    internal var url = "https://api.caiyunapp.com/v2.5/y1S3sjxaYCYMos7N/113.238457,30.415036/weather.json"
    //Toolbar toolbar;
    internal var mHandler: Handler
    private var locationManager: LocationManager? = null
    private var locationProvider: String? = null
    private var smartRefreshLayout: SmartRefreshLayout? = null
    private var locatime = 0//获取定位次数，超过10次取消定位；


    //声明AMapLocationClient类对象
    var mLocationClient: AMapLocationClient? = null

    internal var weatherApi: WeatherApi

    internal var recyclerView_min: RecyclerView
    internal var recyclerView_day: RecyclerView
    internal var recyclerView_hour: RecyclerView

    internal var realtime_comfort: TextView
    internal var realtime_temperature: TextView
    internal var realtime_skycon: TextView
    internal var realtime_ultraviolet: TextView
    internal var realtime_pres: TextView
    internal var realtime_humidity: TextView
    internal var realtime_wind_direction: TextView
    internal var realtime_wind_speed: TextView
    internal var realtime_pm25: TextView
    internal var realtime_pm10: TextView

    internal var result_forecast_keypoint: TextView
    internal var locationListener: LocationListener = object : LocationListener {

        override fun onStatusChanged(provider: String, status: Int, arg2: Bundle) {

        }

        override fun onProviderEnabled(provider: String) {

        }

        override fun onProviderDisabled(provider: String) {

        }

        override fun onLocationChanged(location: Location) {
            //如果位置发生变化,重新显示 如果位置改变，经纬度没有变，不会执行此函数 应该说经纬度发生变化执行此函数
            Log.i("TAG", "经度" + location.longitude + "纬度" + location.latitude)

        }
    }


    private//获取所有可用的位置提供器
    //获取Location
    //如果是GPS
    //不为空,显示地理位置经纬度
    //监视地理位置变化
    //locationManager.requestLocationUpdates(locationProvider, 1000, 1, locationListener);
    //如果是Network
    //不为空,显示地理位置经纬度
    //不为空,显示地理位置经纬度
    //            Intent intent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
    //            startActivityForResult(intent, 0);
    val location: String
        get() {
            locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
            val providers = locationManager!!.getProviders(true)

            if (providers.contains(LocationManager.GPS_PROVIDER)) {
                KLog.d("GPS")
                locationProvider = LocationManager.GPS_PROVIDER

                @SuppressLint("MissingPermission") val location = locationManager!!.getLastKnownLocation(locationProvider!!)
                if (location != null) {
                    KLog.d("GPS:" + "经度" + location.longitude + "纬度" + location.latitude)
                    return location.longitude.toString() + "," + location.latitude
                } else {
                    KLog.d("GPS:" + "没有检测到位置")
                    locatime++
                    if (locatime < 10) {
                        location
                    }
                    return ""
                }
            } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
                locationProvider = LocationManager.NETWORK_PROVIDER
                @SuppressLint("MissingPermission") val location = locationManager!!.getLastKnownLocation(locationProvider!!)
                if (location != null) {
                    KLog.d("NETWORK:" + "经度" + location.longitude + "纬度" + location.latitude)
                    Toast.makeText(this, "GPS定位成功", Toast.LENGTH_SHORT).show()
                    return location.longitude.toString() + "," + location.latitude
                } else {
                    KLog.d("NETWORK:" + "没有检测到位置")
                    return ""
                }
            } else if (providers.contains(LocationManager.PASSIVE_PROVIDER)) {
                locationProvider = LocationManager.PASSIVE_PROVIDER
                locationProvider = LocationManager.NETWORK_PROVIDER
                @SuppressLint("MissingPermission") val location = locationManager!!.getLastKnownLocation(locationProvider!!)
                if (location != null) {
                    KLog.d("PASSIVE:" + "经度" + location.longitude + "纬度" + location.latitude)
                    return location.longitude.toString() + "," + location.latitude
                } else {
                    KLog.d("PASSIVE:" + "没有检测到位置")
                    return ""
                }
            } else {
                Toast.makeText(this, "请打开网络或者GPS，需要获取当前定位信息", Toast.LENGTH_SHORT).show()
                return ""
            }
        }


    @SuppressLint("MissingPermission")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_weather)
        PushAgent.getInstance(applicationContext).onAppStart()

        mHandler = object : Handler() {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                val adapter_p = Min_precipitation_adapter(weatherApi)
                val adapter_t = Day_precipitation_adapter(weatherApi)
                val adapter_c = Hour_skycon_tem_adapter(weatherApi)
                recyclerView_min.adapter = adapter_p//显示recyclerview
                recyclerView_day.adapter = adapter_t
                recyclerView_hour.adapter = adapter_c
                Toast.makeText(this@WeatherActivity, "刷新成功", Toast.LENGTH_SHORT).show()

            }
        }
        recyclerView_min = findViewById<View>(R.id.recyclerView_min) as RecyclerView
        recyclerView_day = findViewById<View>(R.id.recyclerView_day) as RecyclerView
        recyclerView_hour = findViewById<View>(R.id.recyclerView_hour) as RecyclerView
        smartRefreshLayout = findViewById<View>(R.id.refreshLayout) as SmartRefreshLayout
        smartRefreshLayout!!.setRefreshHeader(WaveSwipeHeader(this))
        recyclerView_min.layoutManager = LinearLayoutManager(this, LinearLayout.HORIZONTAL, false)
        val layoutManager = GridLayoutManager(this, 1)
        recyclerView_day.layoutManager = layoutManager
        recyclerView_hour.layoutManager = LinearLayoutManager(this, LinearLayout.HORIZONTAL, false)

        location
        sendRequestWithOkHttp()

        realtime_comfort = findViewById<View>(R.id.realtime_comfort) as TextView
        realtime_temperature = findViewById<View>(R.id.realtime_temperature) as TextView
        realtime_skycon = findViewById<View>(R.id.realtime_skycon) as TextView
        realtime_ultraviolet = findViewById<View>(R.id.realtime_ultraviolet) as TextView
        realtime_pm10 = findViewById<View>(R.id.realtime_pm10) as TextView
        realtime_pm25 = findViewById<View>(R.id.realtime_pm25) as TextView
        realtime_pres = findViewById<View>(R.id.realtime_pres) as TextView
        realtime_humidity = findViewById<View>(R.id.realtime_humidity) as TextView
        realtime_wind_direction = findViewById<View>(R.id.realtime_wind_direction) as TextView
        realtime_wind_speed = findViewById<View>(R.id.realtime_wind_speed) as TextView

        result_forecast_keypoint = findViewById<View>(R.id.result_forecast_keypoint) as TextView

        smartRefreshLayout!!.setOnRefreshListener { refreshlayout ->
            location
            refreshlayout.finishRefresh(2000)
            sendRequestWithOkHttp()
        }
        smartRefreshLayout!!.setOnLoadMoreListener { refreshLayout -> refreshLayout.finishLoadMore(2000) }


    }

    private fun sendRequestWithOkHttp() {
        Thread(Runnable {
            var reurl = ""
            Looper.prepare()
            if (location === "") {
                reurl = url
                KLog.d("老")
            } else {
                reurl = "https://api.caiyunapp.com/v2.5/y1S3sjxaYCYMos7N/$location/weather.json"
                KLog.d("新")
            }

            //在子线程中执行Http请求，并将最终的请求结果回调到okhttp3.Callback中
            HttpUtils.sendOkHttpRequest(reurl, object : okhttp3.Callback {
                @Throws(IOException::class)
                override fun onResponse(call: Call, response: Response) {
                    //得到服务器返回的具体内容
                    val responseData = response.body!!.string()
                    parseJSONWithGSON(responseData)
                    val message = Message()
                    message.obj = responseData
                    mHandler.sendMessage(message)
                }

                override fun onFailure(call: Call, e: IOException) {
                    //在这里进行异常情况处理
                }
            })
            Looper.loop()
        }).start()
    }

    private fun parseJSONWithGSON(jsonData: String) {
        //使用轻量级的Gson解析得到的json
        val gson = Gson()

        //       List<WeatherApi> weatherApiList = gson.fromJson(jsonData, new TypeToken<List<WeatherApi>>() {}.getType());
        //        for (WeatherApi weatherApi : weatherApiList) {
        //            //控制台输出结果，便于查看
        //              Log.d("MainActivity", "other" + weatherApi.getStatus());
        ////            Log.d("MainActivity", "u_Name" + app.getU_Name());
        ////            Log.d("MainActivity", "u_id" + app.getU_id());
        ////            Log.d("MainActivity", "u_passWord" + app.getU_passWord());
        ////            Log.d("MainActivity", "u_token" + app.getU_token());
        //        }

        weatherApi = gson.fromJson(jsonData, WeatherApi::class.java)

        //Log.d("WeatherActivity", "status:" + weatherApi.getStatus());
        Log.d("WeatherActivity", "status:" + weatherApi.result.daily.skycon_20h_32h[3].value)
        //显示UI界面，调用的showResponse方法
        showResponse(weatherApi)

    }

    private fun showResponse(weatherApi: WeatherApi) {
        //在子线程中更新UI
        runOnUiThread {
            // 在这里进行UI操作，将结果显示到界面

            Log.d("MainActivity", weatherApi.result.realtime.temperature.toString())
            result_forecast_keypoint.text = weatherApi.result.forecast_keypoint

            realtime_temperature.text = weatherApi.result.realtime.temperature.toString()
            realtime_skycon.text = Weather_Dict.skycon_dict(weatherApi.result.realtime.skycon)
            realtime_comfort.text = "出门感觉：" + weatherApi.result.realtime.life_index.comfort.desc
            realtime_ultraviolet.text = "紫外线强度：" + weatherApi.result.realtime.life_index.ultraviolet.desc
            realtime_pres.text = "气压：" + weatherApi.result.realtime.pressure + "Pa"
            realtime_humidity.text = "相对湿度：" + weatherApi.result.realtime.humidity + "%"
            realtime_wind_direction.text = "风向：" + Weather_Dict.getWindDirec(weatherApi.result.realtime.wind.direction)
            realtime_wind_speed.text = "风速：" + weatherApi.result.realtime.wind.speed + "km/h"
            realtime_pm25.text = "PM2.5颗粒：" + weatherApi.result.realtime.air_quality.pm25!!
            realtime_pm10.text = "PM1.0颗粒：" + weatherApi.result.realtime.air_quality.pm10!!
            //Toast.makeText(WeatherActivity.this,"天气更新成功",Toast.LENGTH_SHORT).show();
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (locationManager != null) {
            //移除监听器
            locationManager!!.removeUpdates(locationListener)
        }
    }


}
